import { NAV_WIDTH, HEADER_HEIGHT } from '@/layouts/dashboard/config';
import { useSettings } from '@/store/settingStore';
import { ThemeLayout } from '@/types/enum';
import React, { useEffect, useRef, useState } from 'react';

interface ResizeProps {
  width: number;
  minWidth?: number;
  maxWidth?: number;
}

const useDragResize = ({ width, minWidth = width, maxWidth = width * 2 }: ResizeProps) => {
  const [resizeWidth, setResizeWidth] = useState(width);
  const dragging = useRef(false);
  const layoutWidth = useRef(0);
  const { themeLayout } = useSettings();

  const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    dragging.current = true;
  };

  const handleMouseMove = (event: any) => {
    event.preventDefault();
    event.stopPropagation();
    if (dragging.current) {
      const newWidth = event.clientX - layoutWidth.current; // 获取鼠标的位置
      if (newWidth >= maxWidth) {
        setResizeWidth(maxWidth);
        return;
      }

      if (newWidth <= minWidth) {
        setResizeWidth(minWidth);
        return;
      }
      setResizeWidth(newWidth);
    }
  };

  useEffect(() => {
    layoutWidth.current =
      themeLayout === ThemeLayout.Vertical ? NAV_WIDTH + 16 + 8 : HEADER_HEIGHT + 16 + 8;
  }, [themeLayout]);

  const handleMouseUp = () => {
    dragging.current = false;
  };

  useEffect(() => {
    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', handleMouseUp);

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, []);

  return [resizeWidth, handleMouseDown] as const;
};

export default useDragResize;
